<?php
#所有的系统函数都在这里

#加密快捷方法
function encode($string,$key = '', $expiry = 0){
   $key=$key?$key:AUTH_KEY;
   return authCode($string, 'ENCODE' , $key, $expiry);
}
#解密快捷方法
function decode($string, $key = '', $expiry = 0){
   $key=$key?$key:AUTH_KEY;
   return authCode($string,'DECODE', $key , $expiry);
}
#$_GET快捷方法
function G($key=''){
        return httpGet($key);
}
#$_POST快捷方法
function P($key=''){
        return httpPost($key);
}
#$_COOKIE快捷方法
function C($key=''){
        return httpCcookie($key);
}
#$_SERVER快捷方法
function S($key=''){
        return httpServer($key);
}
#过滤掉所有魔法转义
function stripslashes_all(){
      if(!get_magic_quotes_gpc()){return;}
      $strip_list=array('$_GET','$_POST','$_COOKIE');
      foreach($strip_list as $val){
             eval("$val=stripslashes2($val);");
      }
}
/**
 * 分页函数
 * @param int $total    总页数
 * @param int $pagesize 每页几条
 * @param string $pkey  url中页面变量名称
 * @param string $url   完整的搜索url，其中的{page}会被替换为页码
 * 依赖函数 request_uri httpInt
 */
function page($total,$pagesize=10,$pkey='p',$url=null){
    $a_num=10;
    $first=' 首页 ';
    $last=' 尾页 ';
    $pre=' 上页 ';
    $next=' 下页 ';
    $a_num=$a_num%2==0?$a_num+1:$a_num;
    if(!$url){
        $url=preg_replace("/&?{$pkey}=[^&]{0,}/", '',request_uri());
        $url=strpos($url, '?')===FALSE?$url.'?'.$pkey.'={page}':$url.'&'.$pkey.'={page}';
    }
    $pages=ceil($total/$pagesize);
    $curpage=httpInt($pkey,false,1);
    $curpage=$curpage>$pages||$curpage<=0?1:$curpage;#当前页超范围置为1
    $body='';$prefix='';$subfix='';
    $start=$curpage-($a_num-1)/2;#开始页
    $end=$curpage+($a_num-1)/2;  #结束页
    $start=$start<=0?1:$start;   #开始页超范围修正
    $end=$end>$pages?$pages:$end;#结束页超范围修正
    if($pages>=$a_num){#总页数大于显示页数
        if($curpage<=($a_num-1)/2){$end=$a_num;}//当前页在左半边补右边
        if($end-$curpage<=($a_num-1)/2){$start-=5-($end-$curpage);}//当前页在右半边补左边
    }
    for($i=$start;$i<=$end;$i++){
         if($i==$curpage){
             $body.='<b>'.$i.'</b>';
         }else{
             $body.='<a href="'.str_replace('{page}',$i,$url).'"> '.$i.' </a>';
         }
    }
    $prefix=($curpage==1?'':'<a href="'.str_replace('{page}',1,$url).'">'.$first.'</a><a href="'.str_replace('{page}',$curpage-1,$url).'">'.$pre.'</a>');
    $subfix=($curpage==$pages?'':'<a href="'.str_replace('{page}',$curpage+1,$url).'">'.$next.'</a><a href="'.str_replace('{page}',$pages,$url).'">'.$last.'</a>');
    $info=" 第{$curpage}/{$pages}页 ";
    $go='<script>function ekup(){if(event.keyCode==13){clkyup();}}function clkyup(){var num=document.getElementById(\'gsd09fhas9d\').value;if(!/^\d+$/.test(num)||num<=0||num>'.$pages.'){alert(\'请输入正确页码!\');return;};location=\''.$url.'\'.replace(/\\{page\\}/,document.getElementById(\'gsd09fhas9d\').value);}</script><input onkeyup="ekup()" type="text" id="gsd09fhas9d" style="width:40px;vertical-align:text-baseline;padding:0 2px;font-size:10px;border:1px solid gray;"/> <span id="gsd09fhas9daa" onclick="clkyup();" style="cursor:pointer;text-decoration:underline;">转到</span>';
    return $prefix.$body.$subfix.$info.$go;
}
/**
* 输出验证码，同时设置加密的cookie[$vali]，服务端验证验证码时通过比较解密后的cookie[$vali]和用户输入的验证码
* @$vali cookie中验证码的键名称
* 依赖函数random、authCode、valiCode
* 依赖常量 AUTH_KEY
*/
function valimg($vali='cuin'){
    $code=random(4,'both');
    setcookie($vali,authCode($code,'ENCODE',AUTH_KEY,20));
    $_COOKIE[$vali]=$code;
    valiCode($code);
}
/* setcookie重写
*依赖函数 S
*/
function setCookie2($key,$value,$life=null,$path='/',$domian=null){
     header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
     setcookie($key, $value,($life?$life+time():null),$path,($domian?$domian:S('HTTP_HOST')),(S('SERVER_PORT') == 443 ? 1 : 0));
     $_COOKIE[$key]=$value;
}
/* 设置加密cookie
*  依赖函数 encode
*  依赖常量 AUTH_KEY
*/
function setEnCookie($key,$value,$life=null,$path='/',$domian=null){
     $value=encode($value,AUTH_KEY);
     header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
     setcookie($key, $value,($life?$life+time():null),$path,($domian?$domian:S('HTTP_HOST')), (S('SERVER_PORT') == 443 ? 1 : 0));
     $_COOKIE[$key]=$value;
}
/* 获得加密cookie
*  依赖函数 C decode
*  依赖常量 AUTH_KEY
*  @$key COOKIE中的键名称
*  @return 解密后的cookie字符串
*/
function C2($key){
        return C($key)?decode(C($key),AUTH_KEY):null;
}
/**
#返回<script>标记，用于引用js文件
#依赖常量 RESOURCE_LINK
*/
function script($jsname){
     return '<script src="'.RESOURCE_LINK.$jsname.'.js" type="text/javascript"></script>';
}
/**
#返回<link>标记，用于引用css文件
#依赖常量 RESOURCE_LINK
*/
function cssLink($cssname){
     return '<link rel="stylesheet" type="text/css" href="'.RESOURCE_LINK.$cssname.'.css" />';
}
/**
#返回img src链接，用于引用图片文件
#依赖常量 RESOURCE_LINK
*/
function img($imgname){
     return RESOURCE_LINK.$imgname;
}
/**
* 访问日志记录
*
* @author 狂奔的蜗牛
* @return bool
#依赖函数 getSpiderAgent
#依赖常量 SITE_LOG_SAVE_PATH
*/
function siteLog($stop_log=false) {
     if($stop_log){return;}
     if(!isset($_COOKIE['mkvd'])){
           $flag=false;
           $spider='';
           $agent= strtolower($_SERVER['HTTP_USER_AGENT']); 
           if (!empty($agent)) { 
           $spiderSite=getSpiderAgent();
           foreach($spiderSite as $val) { 
           $str = strtolower($val); 
           if (strpos($agent, $str) !== false) {
               $spider=$str;
               $flag=true;
               break;
           }
           }
           }
           $referer=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'null';
           $requri=$_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:'null';
           $ip=$_SERVER['REMOTE_ADDR']?$_SERVER['REMOTE_ADDR']:'null';
           $agent=$agent?$agent:'null';
           $isspider=$flag?'[Spider]:'.$spider:'';
           $max_size=1024*1024*3;#单个日志文件最大值 3M
           $logpath=SITE_LOG_SAVE_PATH;
           $logfilename=$logpath.'visit.log';
           $logfilename_old=$logpath.'visit_old.log';
           $logfilename_spider=$logpath.'visit_spider.log';
           $logfilename_old_spider=$logpath.'visit_old_spider.log';
           $end_logfilename='';
           if($flag){
                 #蜘蛛
                 if(file_exists($logfilename_spider)){
                     if(filesize($logfilename_spider)>$max_size){
                         if(file_exists($logfilename_old)){unlink($logfilename_old_spider);}
                         if(!rename($logfilename_spider,$logfilename_old_spider)){unlink($logfilename_spider);}
                    }
                }
                $end_logfilename=$logfilename_spider;
           }else{
                 #访问者
                 if(file_exists($logfilename)){
                     if(filesize($logfilename)>$max_size){
                         if(file_exists($logfilename_old)){unlink($logfilename_old);}
                         if(!rename($logfilename,$logfilename_old)){unlink($logfilename);}
                    }
                }
                $end_logfilename=$logfilename;
           }
           file_put_contents(
           $end_logfilename,'==>'.
            '[Time]:'.date('Y-m-d H:i:s').$isspider.
           '--[RequestURL]:'.$requri.
           '--[IP]:'.$ip.
           '--[Agent]:'.$agent.
           '--[Referer]:'.$referer.
           "\n", FILE_APPEND);
           setcookie('mkvd',rand(100000,999999),null,'/');
     }
} 

#获取GET变量
function httpGet($key=''){
       if($key){
             return isset($_GET[$key])?$_GET[$key]:false;
       }else{
            return $_GET;
       }
}
#获取POST变量
function httpPost($key=''){
       if($key){
             return isset($_POST[$key])?$_POST[$key]:false;
       }else{
             return $_POST;
       }
}
#获取Ccookie变量
function httpCcookie($key=''){
       if($key){
             return isset($_COOKIE[$key])?$_COOKIE[$key]:false;
       }else{
            return $_COOKIE;
       }
}
#获取SERVER变量
function httpServer($key=''){
       if($key){
             return isset($_SERVER[$key])?$_SERVER[$key]:false;
       }else{
            return $_SERVER;
       }
}
/**
 * 获取HTTP传递的浮点数
 * @param string $key 参数名称
 * @param bool $ispost 采取POST传递方式，默认为真
 * @return 整数，非法时默认为 $default
 */
function httpFloat($key, $ispost=true,$default=0) {
    if ($ispost) {
        if (isset($_POST[$key])) {
            if (empty($_POST[$key])) {
                return $default;
            } else {
                $val = trim($_POST[$key]);
                if (preg_match("/^\d+\.\d+$/", $val)) return floatval($val);
                elseif (preg_match("/^\d+$/", $val)) return intval($val);
                else return $default;
            }
        } else {
            return $default;
        }
    } else {
        if (isset($_GET[$key])) {
            if (empty($_GET[$key])) {
                return $default;
            } else {
                $val = trim($_GET[$key]);
                if (preg_match("/^\d+\.\d+$/", $val)) return floatval($val);
                elseif (preg_match("/^\d+$/", $val)) return intval($val);
                else return $default;
            }
        } else {
            return $default;
        }
    } 
}
/**
 * 获取HTTP传递的整数
 * @param string $key 参数名称
 * @param bool $ispost 采取POST传递方式，默认为真
 * @return 整数，非法时默认为 $default
 */
function httpInt($key, $ispost=true,$default=0) {
    if ($ispost) {
        if (isset($_POST[$key])) {
            if (empty($_POST[$key])) {
                return $default;
            } else {
                $val = trim($_POST[$key]);
                if (preg_match("/^\-?\d+$/", $val)) return intval($val);
                else return $default;
            }
        } else {
            return $default;
        }
    } else {
        if (isset($_GET[$key])) {
            if (empty($_GET[$key])) {
                return $default;
            } else {
                $val = trim($_GET[$key]);
                if (preg_match("/^\-?\d+$/", $val)) {
                    return intval($val);
                } else {
                    return $default;
                }
            }
        } else {
            return $default;
        }
    }
}
/**
 * 获取HTTP传递的布尔值
 * @param string $key 参数名称
 * @param bool $ispost 采取POST传递方式，默认为真
 * @return 布尔值，默认为FALSE，只有值为“1”时才为真
 */
function httpBool($key, $ispost=true,$default=false) {
    if ($ispost) {
        if (isset($_POST[$key])) {
            if (empty($_POST[$key])) return $default;
            else return trim($_POST[$key]) === "1";
        } else {
            return $default;
        }
    } else {
        if (isset($_GET[$key])) {
            if (empty($_GET[$key])) return $default;
            else return trim($_GET[$key]) === "1";
        } else {
            return $default;
        }
    }
}
/**
 * 获取HTTP传递的字符串
 * @param string $key 参数名称
 * @param bool $ispost 采取POST传递方式，默认为真
 * @param bool $istrim 是否删除两端空白，默认为真
 * @return 字符串，默认为空串
 */
function httpString($key, $ispost=true, $istrim=true) {
    # 非UTF－8空字符过滤
    if ('' == iconv('UTF-8', 'UTF-8', $key)) {
        return '';
    }
    if ($ispost) {
        if (isset($_POST[$key])) {
            if ('' == strval($_POST[$key])) {
                return "";
            } else {
                $val = $_POST[$key];
                if ($istrim) {
                    return trim($val);
                } else {
                    return $val;
                }
            }
        } else {
            return "";
        }
    } else {
        if (isset($_GET[$key])) {
            if ('' == strval($_GET[$key])) {
                return "";
            } else {
                $val = $_GET[$key];
                if ($istrim) {
                    return trim($val);
                } else {
                    return $val;
                }
            }
        } else {
            return "";
        }
    }
}
/**
 * 获取请求客户端IP
 * @return ip
 */
function httpIp(){
    if (getenv('SERVER_SOFTWARE') == 'nginx'){
        if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
            $ip = getenv('REMOTE_ADDR');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
            $ip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else {
            $ip = '127.0.0.1';
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
            $ip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else {
            $ip = '127.0.0.1';
        }
    }
    preg_match("/[\d\.]{7,15}/", $ip, $temp);
    $ip = $temp[0] ? $temp[0] : 'unknown';
    unset($temp);
    if (isset($_SERVER["HTTP_CDN_SRC_IP"])){
        $ip = $_SERVER["HTTP_CDN_SRC_IP"];
    }
    return $ip;
}
#过滤魔法转义，参数可以是字符串或者数组，支持嵌套数组
function stripslashes2($var){
    if(!get_magic_quotes_gpc()){return $var;}
    if(is_array($var)){
         foreach($var as $key=>$val){
                if(is_array($val)){
                    $var[$key] =stripslashes2($val);
                }else{
                    $var[$key] = stripslashes($val);
                }
            }
    }elseif(is_string($var)){
              $var= stripslashes($var);
    }
    return $var;
}
/**
 * 字符串加密以及解密函数
 *
 * @param string $string 原文或者密文
 * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
 * @param string $key 密钥
 * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
 *
 * @example
 *
 *     $a = authcode('abc', 'ENCODE', 'key');
 *     $b = authcode($a, 'DECODE', 'key');  # $b(abc)
 *
 *     $a = authcode('abc', 'ENCODE', 'key', 3600);
 *     $b = authcode('abc', 'DECODE', 'key'); # 在一个小时内，$b(abc)，否则 $b 为空
 */
function authCode($string, $operation = 'DECODE', $key, $expiry = 0) {
    $ckey_length = 4;    # 随机密钥长度 取值 0-32;
                # 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
                # 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
                # 当此值为 0 时，则不产生随机密钥
    $key = md5($key);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}
/**
 * ip2long 重写
 * @param string $ip ip地址
 * @return string ip的long型字符串
 */
function ip2long2($ip = '127.0.0.1') {
    $long = ip2long($ip);
    if ($long == -1 || $long === false){
        return sprintf('%u', ip2long('127.0.0.1'));
    } else {
        return sprintf('%u', $long);
    }
}
/**
 * strip_tags 重写
 * @param string $string 同strip_tags
 * @param string $string 同allowable_tags
 * @return string
 */
function strip_tags2($string, $allowable_tags = '') {
    $string = trim($string);
    # 去除 css
    $string = preg_replace('/<style>.*?<\/style>/i', '', $string);
    $string = strip_tags($string);
    $string = trim($string);
    # 去除中文空格
    $string = preg_replace('/^(　)+/', '', $string);
    # 去除不完整的HTML
    $string = preg_replace('/<.*?>/', '', $string);
    # HTML编码转换
    $string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&lt;', '&gt;'), array(' ', '&', '"', '<', '>'), $string);
    return $string;
}
/**
 * @name str_seq_replace(($heystack,$search,$to,$seq))
 * @param String $heystack 目标搜索字符串
 * @param String $search  关键字
 * @param String $to      替换为
 * @param Int    $seq   替换匹配关键字的次序,从0计数
 * @return string 替换后的字符串
 */
function str_seq_replace($heystack,$search,$to,$seq){
    $arrStar=array();
    $sequence=0;
    $strCompare=null;
    $arr=str_split($heystack);
    foreach($arr as $k=>$v){
        $len=strlen($search);
        while($len>0 && $k<count ($arr)){
            $strCompare.=$arr[$k++];
            $len--;
        }
        if($strCompare === $search) $arrStar[]=$k-strlen($search);
        $strCompare=null;
    }
    $replacedStr=substr_replace($heystack,$to,$arrStar[$seq],strlen($search));
    return $replacedStr;
}
/**
 * 去除关联数组第一个$key=>$val。
 *
 * @param array $source 源关联数组
 * @return array 被去除的数组项
 */
function assocPopHead(array &$source){
   if(empty($source)){
       return array();
   }
   $key = array_shift(array_keys($source));
   $value = $source[$key];
   unset($source[$key]);
   return array($key => $value);
}
/**
 * 在关联数组第一位插入一个关联数组,类似合并数组。
 *
 * @param array $source 源关联数组
 * @param array $insert 要插入的关联数组
 */
function assocPushHead(array &$source, array $insert){
    $temp = $source;
    $source = $insert;
    assocPush($source, $temp);
    unset($temp);
}
/**
 * 去除关联数组最后一个关联数组。
 *
 * @param array $source 源关联数组
 * @return array 被去除的数组项
 */
function assocPop(array &$source){
   if(empty($source)){
       return array();
   }
   $key = array_pop(array_keys($source));
   $value = $source[$key];
   unset($source[$key]);
   return array($key => $value);
}
/**
 * 在关联数组最后一位插入一个关联数组,类似合并数组。
 *
 * @param array $source 源关联数组
 * @param array $insert 要插入的关联数组
 */
function assocPush(array &$source, array $insert){
   foreach ($insert as $key=>$value){
       $source[$key] = $value;
   }
}
/** microtime重写
 * returns the current Unix timestamp with microseconds
 */
function microtime2() {
    if (PHP_VERSION >= '5.0') {
        return microtime(true);
    } else {
        $mtime = explode(' ', microtime());
        return $mtime[1] + $mtime[0];
    }
}
/**
 * 获取星期的中文格式
 *
 * @param int $time 日期格式的UNIX秒数
 * @return string
 */
function week($time = 0) {
    $time = intval($time);
    if($time == 0){
        $time = time();
    }
    $arr = array(
      1 => '星期一',
      2 => '星期二',
      3 => '星期三',
      4 => '星期四',
      5 => '星期五',
      6 => '星期六',
      7 => '星期日'
    );
    $week = intval(date('N', $time));
    if(isset($arr[$week])){
        return $arr[$week];
    } else {
        return '未定义';
    }
}
/**
 * 将字节格式化成指定的单位表示
 * @param float $byte 文件的大小
 * @param string $unit 单位，可用的单位为：a、b、k、m、g，不区分大小写，其中a为程序自动判断
 * @param bool $include_unit 是否包含单位
 * @return string
 */
function scalar($byte, $unit = 'a', $include_unit = true) {
    $arr = array(
       'b' => array(1, 'B'),
       'k' => array(1024, 'KB'),
       'm' => array(1024 * 1024, 'MB'),
       'g' => array(1024 * 1024 * 1024, 'GB')
   );
   $unit = strtolower($unit);
   if($unit == 'a'){
       foreach ($arr as $key=>$value) {
           if($byte > $value[0] * 0.9){
               $unit = $key;
           } else {
               break;
           }
       }
   }
   if(isset($arr[$unit])){
       $byte = $byte / $arr[$unit][0];
   } else {
       $byte = 0;
   }
   $byte = sprintf("%.2f", $byte);
   $byte = preg_replace('/\.?0+$/', '', $byte);
   return $byte . ($include_unit ? $arr[$unit][1] : '');
}
/**
 * 随机产生指定长度的字符串，包含字母和数字
 * @param int $length 字符串长度
 * @param int $type 返回的字符串类型
 * @return 随机字符串
 */
function random($length, $type = 'visible') {
    $hash = '';
    $chararr =array(
        'both' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz',
        'char' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'num' => '0123456789',
        'visible' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz`~@#$%^&*()-_+=|\}}{{<,>.?/"\':;'
    );
    $chars=$chararr[$type];
    $max = strlen($chars) - 1;
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
/**
 * PHP截取UTF-8字符串，解决半字符问题。英文、数字（半角）为1字节（8位），中文（全角）为3字节
 * @param string $str  源字符串
 * @param string $from 截取的开始点，0是起始位置
 * @param int $len     子串的长度，一个字符算一个长度
 * @param string $dot 后缀
 * @return 取出的字符串
 */
function utf8Substr($str, $from, $len,$dot='')
{
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str).$dot;
}
/*
#  把中文字符串转为数组
#  $charset变量为字符串编码，如"gb2312"或"utf-8"；
#  使用方法一要求服务器必须开启mbstring.dll扩展，否则代码执行错误
*/
function mbstringtoarray($str,$charset) {
    $strlen=mb_strlen($str);
    while($strlen){
        $array[]=mb_substr($str,0,1,$charset);
        $str=mb_substr($str,1,$strlen,$charset);
        $strlen=mb_strlen($str);
    }
    return $array;
}
#取得字符串的长度，包括中英文。一个汉字、一个字母或数字都按长度1计算
function getStringLength($text){
   if (function_exists('mb_substr')) {
     $length=mb_strlen($text,'UTF-8');
   } elseif (function_exists('iconv_substr')) {
     $length=iconv_strlen($text,'UTF-8');
   } else {
     preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
     $length=count($ar[0]);

   }
   return $length;
}
#js的escape在php中的实现
function escape($string) {
    $n = $bn = $tn = 0;
    $output = '';
    $special = "-_.+@/*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    while($n < strlen($string)) {
            $ascii = ord($string[$n]);
            if($ascii == 9 || $ascii == 10 || (32 <= $ascii && $ascii <= 126)) {
                    $tn = 1;$n++;
            } elseif(194 <= $ascii && $ascii <= 223) {
                    $tn = 2;$n += 2;
            } elseif(224 <= $ascii && $ascii <= 239) {
                    $tn = 3;$n += 3;
            } elseif(240 <= $ascii && $ascii <= 247) {
                    $tn = 4;$n += 4;
            } elseif(248 <= $ascii && $ascii <= 251) {
                    $tn = 5;$n += 5;
            } elseif($ascii == 252 || $ascii == 253) {
                    $tn = 6;$n += 6;
            } else {
                    $n++;
            }
            $singleStr = substr($string,$bn,$tn);
            $charVal = bin2hex(iconv('utf-8', 'ucs-2', $singleStr));
            if(base_convert($charVal, 16, 10) > 0xff) {
                    if (!preg_match("/win/i", PHP_OS)){
        $charVal = substr($charVal, 2, 2) . substr($charVal, 0, 2);
    }
                    $output .= '%u' . $charVal;
            } else {
                    if(false !== strpos($special, $singleStr)) {
                            $output .= $singleStr;
                    } else {
                            $output .="%" . dechex(ord($string[$bn]));
                    }
            }
            $bn = $n;
    }
    return $output;
}
#js的unescape在php中的实现
function unescape($str)
{
    $str = rawurldecode($str);
    preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U", $str, $r);
    $ar = $r[0];
    #print_r($ar);
    foreach($ar as $k=>$v)
    {
            if(substr($v,0,2) == "%u")
                    $ar[$k] = iconv("UCS-2", "UTF-8", pack("H4",substr($v,-4)));
            elseif(substr($v,0,3) == "&#x")
                    $ar[$k] = iconv("UCS-2", "UTF-8", pack("H4",substr($v,3,-1)));
            elseif(substr($v,0,2) == "&#")
            {
                    //echo substr($v,2,-1)."";
                    $ar[$k] = iconv("UCS-2", "UTF-8", pack("n",substr($v,2,-1)));
            }
    }
    return join("",$ar);
}
/**
#函数名: compress_html
#参数: $string
#返回值: 压缩后的$string
#在网页中唯一需要注意的是<script>中不要使用 "//" 进行注释,不然会导致js代码出错，换用/* * /进行注释。
*/
function compress_html($string) {
    $string = str_replace("\r\n", '', $string); #清除换行符
    $string = str_replace("\n", '', $string); #清除换行符
    $string = str_replace("\t", '', $string); #清除制表符
    $pattern = array (
                    "/> *([^ ]*) *</", #去掉注释标记
                    "/[\s]+/",
                    "/<!--[\\w\\W\r\\n]*?-->/",
                    "/\" /",
                    "/ \"/",
                    "'/\*[^*]*\*/'"
                    );
    $replace = array (
                    ">\\1<",
                    " ",
                    "",
                    "\"",
                    "\"",
                    ""
                    );
    return preg_replace($pattern, $replace, $string);
} 

 /**
 *  将传入的字符串写到验证码图片上，并向浏览器输出验证码图片
 */
function valiCode($randstr){
    Header("Content-type: image/gif");
    $border = 0; #是否要边框 1要:0不要
    $how = strlen($randstr); #验证码位数
    $w = $how*15; #图片宽度
    $h = 18; #图片高度
    $fontsize = 12; #字体大小
    srand((double)microtime()*1000000); #初始化随机数种子
    $im = ImageCreate($w, $h); #创建验证图片
    /*
    * 绘制基本框架
    */
    $bgcolor = ImageColorAllocate($im, 255, 255, 255); #设置背景颜色
    ImageFill($im, 0, 0, $bgcolor); #填充背景色
    if($border)
    {
        $black = ImageColorAllocate($im, 0, 0, 0); #设置边框颜色
        ImageRectangle($im, 0, 0, $w-1, $h-1, $black);#绘制边框
    }
    /*
    * 逐位产生随机字符
    */
    for($i=0; $i<$how; $i++)
    {
        $j = !$i ? $how : $j+15; #绘字符位置
        $color3 = ImageColorAllocate($im, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100)); #字符随即颜色
        ImageChar($im, $fontsize, $j, 3, $randstr{$i}, $color3); #绘字符
    }
    /*
    * 如果需要添加干扰就将注释去掉
    *
    * 以下for()循环为绘背景干扰线代码
    */
    /* + -------------------------------绘背景干扰线 开始-------------------------------------------- + */
    for($i=0; $i<5; $i++)#绘背景干扰线
    {
        $color1 = ImageColorAllocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); #干扰线颜色
        ImageArc($im, mt_rand(-5,$w), mt_rand(-5,$h), mt_rand(20,300), mt_rand(20,200), 55, 44, $color1); #干扰线
    }
    /* + -------------------------------绘背景干扰线 结束-------------------------------------- + */
    /*
    * 如果需要添加干扰就将注释去掉
    *
    * 以下for()循环为绘背景干扰点代码
    */
    /* + --------------------------------绘背景干扰点 开始------------------------------------------ + */
    for($i=0; $i<$how*40; $i++)#绘背景干扰点
    {
        $color2 = ImageColorAllocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); #干扰点颜色
        ImageSetPixel($im, mt_rand(0,$w), mt_rand(0,$h), $color2); #干扰点
    }
    /* + --------------------------------绘背景干扰点 结束------------------------------------------ + */
    /*绘图结束*/
    Imagegif($im);
    ImageDestroy($im);
    /*绘图结束*/
}
/**
 * 是否是邮箱
 * @param $email 邮箱
 * @return bool
 */
function isEmail($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}
/**
 * 是否是手机号码
 * @param $mobile 手机号码
 * @return bool
 */
function isMobile($mobile) {
    if (filter_var($mobile, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^(130|131|132|133|134|135|136|137|138|139|147|150|151|152|153|155|156|157|158|159|180|182|185|186|187|188|189)[0-9]{8}$/i')))) {
        return true;
    } else {
        return false;
    }
}
/**
 * 说明：获取 _SERVER['REQUEST_URI'] 值的通用解决方案
 */
function request_uri()
{
    if (isset($_SERVER['REQUEST_URI']))
    {
        $uri = $_SERVER['REQUEST_URI'];
    }
    else
    {
        if (isset($_SERVER['argv']))
        {
            $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
        }
        else
        {
            $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
        }
    }
    return $uri;
}
/*
#汉字转拼音
#$_String 汉字
#$_Code  汉字的编码，默认utf-8
#依赖函数 _Pinyin _U2_Utf8_Gb _Array_Combine
*/
function pinyin($_String, $_Code='utf-8'){
        $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
        $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274|-10270|-10262|-10260|-10256|-10254";
        $_TDataKey = explode('|', $_DataKey);
        $_TDataValue = explode('|', $_DataValue);
        $_Data = (PHP_VERSION>='5.0') ? array_combine($_TDataKey, $_TDataValue) : _Array_Combine($_TDataKey, $_TDataValue);
        arsort($_Data);
        reset($_Data);
        if($_Code != 'gb2312') $_String = _U2_Utf8_Gb($_String);
        $_Res = '';
        for($i=0; $i<strlen($_String); $i++)
        {
        $_P = ord(substr($_String, $i, 1));
        if($_P>160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536; }
        $_Res .= _Pinyin($_P, $_Data);
        }
        $_Res=preg_replace("/[^A-Z_\\-a-z0-9]*/", '', $_Res);
        $_Res=strtolower($_Res);
        return $_Res; 
}
#pinyin依赖函数
function _Pinyin($_Num, $_Data){
        if ($_Num>0 && $_Num<160 ) return chr($_Num);
        elseif($_Num<-20319 || $_Num>-10247) return '';
        else {
        foreach($_Data as $k=>$v){ if($v<=$_Num) break; }
        return $k;
        }
}
#pinyin依赖函数
function _U2_Utf8_Gb($_C){
        $_String = '';
        if($_C < 0x80) $_String .= $_C;
        elseif($_C < 0x800)
        {
        $_String .= chr(0xC0 | $_C>>6);
        $_String .= chr(0x80 | $_C & 0x3F);
        }elseif($_C < 0x10000){
        $_String .= chr(0xE0 | $_C>>12);
        $_String .= chr(0x80 | $_C>>6 & 0x3F);
        $_String .= chr(0x80 | $_C & 0x3F);
        } elseif($_C < 0x200000) {
        $_String .= chr(0xF0 | $_C>>18);
        $_String .= chr(0x80 | $_C>>12 & 0x3F);
        $_String .= chr(0x80 | $_C>>6 & 0x3F);
        $_String .= chr(0x80 | $_C & 0x3F);
        }
        return iconv('UTF-8', 'GB2312', $_String);
}
#pinyin依赖函数
function _Array_Combine($_Arr1, $_Arr2){
        for($i=0; $i<count($_Arr1); $i++) $_Res[$_Arr1[$i]] = $_Arr2[$i];
        return $_Res;
}
/**
 * 强制下载
 * 经过修改，支持中文名称
 * Generates headers that force a download to happen
 *
 * @access    public
 * @param    string    filename
 * @param    mixed    the data to be downloaded
 * @return    void
 */
function force_download($filename = '', $data = ''){
        if ($filename == '' OR $data == '')
        {
            return FALSE;
        }
        # Try to determine if the filename includes a file extension.
        # We need it in order to set the MIME type
        if (FALSE === strpos($filename, '.'))
        {
            return FALSE;
        }
        # Grab the file extension
        $x = explode('.', $filename);
        $extension = end($x);
        # Load the mime types
        $mimes=array('hqx'=>'application/mac-binhex40','cpt'=>'application/mac-compactpro','csv'=>array('text/x-comma-separated-values','text/comma-separated-values','application/octet-stream','application/vnd.ms-excel','application/x-csv','text/x-csv','text/csv','application/csv','application/excel','application/vnd.msexcel'),'bin'=>'application/macbinary','dms'=>'application/octet-stream','lha'=>'application/octet-stream','lzh'=>'application/octet-stream','exe'=>array('application/octet-stream','application/x-msdownload'),'class'=>'application/octet-stream','psd'=>'application/x-photoshop','so'=>'application/octet-stream','sea'=>'application/octet-stream','dll'=>'application/octet-stream','oda'=>'application/oda','pdf'=>array('application/pdf','application/x-download'),'ai'=>'application/postscript','eps'=>'application/postscript','ps'=>'application/postscript','smi'=>'application/smil','smil'=>'application/smil','mif'=>'application/vnd.mif','xls'=>array('application/excel','application/vnd.ms-excel','application/msexcel'),'ppt'=>array('application/powerpoint','application/vnd.ms-powerpoint'),'wbxml'=>'application/wbxml','wmlc'=>'application/wmlc','dcr'=>'application/x-director','dir'=>'application/x-director','dxr'=>'application/x-director','dvi'=>'application/x-dvi','gtar'=>'application/x-gtar','gz'=>'application/x-gzip','php'=>'application/x-httpd-php','php4'=>'application/x-httpd-php','php3'=>'application/x-httpd-php','phtml'=>'application/x-httpd-php','phps'=>'application/x-httpd-php-source','js'=>'application/x-javascript','swf'=>'application/x-shockwave-flash','sit'=>'application/x-stuffit','tar'=>'application/x-tar','tgz'=>array('application/x-tar','application/x-gzip-compressed'),'xhtml'=>'application/xhtml+xml','xht'=>'application/xhtml+xml','zip'=>array('application/x-zip','application/zip','application/x-zip-compressed'),'mid'=>'audio/midi','midi'=>'audio/midi','mpga'=>'audio/mpeg','mp2'=>'audio/mpeg','mp3'=>array('audio/mpeg','audio/mpg','audio/mpeg3','audio/mp3'),'aif'=>'audio/x-aiff','aiff'=>'audio/x-aiff','aifc'=>'audio/x-aiff','ram'=>'audio/x-pn-realaudio','rm'=>'audio/x-pn-realaudio','rpm'=>'audio/x-pn-realaudio-plugin','ra'=>'audio/x-realaudio','rv'=>'video/vnd.rn-realvideo','wav'=>'audio/x-wav','bmp'=>'image/bmp','gif'=>'image/gif','jpeg'=>array('image/jpeg','image/pjpeg'),'jpg'=>array('image/jpeg','image/pjpeg'),'jpe'=>array('image/jpeg','image/pjpeg'),'png'=>array('image/png','image/x-png'),'tiff'=>'image/tiff','tif'=>'image/tiff','css'=>'text/css','html'=>'text/html','htm'=>'text/html','shtml'=>'text/html','txt'=>'text/plain','text'=>'text/plain','log'=>array('text/plain','text/x-log'),'rtx'=>'text/richtext','rtf'=>'text/rtf','xml'=>'text/xml','xsl'=>'text/xml','mpeg'=>'video/mpeg','mpg'=>'video/mpeg','mpe'=>'video/mpeg','qt'=>'video/quicktime','mov'=>'video/quicktime','avi'=>'video/x-msvideo','movie'=>'video/x-sgi-movie','doc'=>'application/msword','docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document','xlsx'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','word'=>array('application/msword','application/octet-stream'),'xl'=>'application/excel','eml'=>'message/rfc822','json'=>array('application/json','text/json'));
        # Set a default mime if we can't find it
        if ( ! isset($mimes[$extension]))
        {
            $mime = 'application/octet-stream';
        }
        else
        {
            $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
        }
        header('Content-Type: "'.$mime.'"');
        $tmpName=$filename;
        $filename='"'.urlencode($tmpName).'"';#ie中文文件名支持
        if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']),'firefox')!= false){$filename='"'.$tmpName.'"';}#firefox中文文件名支持
        if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']),'chrome')!= false){$filename=urlencode($tmpName);}#Chrome中文文件名支持
        header('Content-Disposition: attachment; filename='.$filename);
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header("Content-Transfer-Encoding: binary");
        header('Pragma: no-cache');
        header("Content-Length: ".strlen($data));
        exit($data);
}
/**
#把数据转换为json数据，用于处理ajax请求
*@$status 状态码
*@$info   字符串信息
*@$msg    数据数组
*@return  json字符串
*/
function ajaxEcho($code,$hint='',$data=array(),$return=false){
    if($return){
        return '{"code":'.$code.',"hint":"'.$hint.'","data":'.json_encode($data).'}';
    }else{
        echo '{"code":'.$code.',"hint":"'.$hint.'","data":'.json_encode($data).'}';
    }
     
}
#返回蜘蛛的agent标志数组
function getSpiderAgent(){
    return array("TencentTraveler","Baiduspider","BaiduGame","Googlebot","msnbot","Sosospider","Sogouwebspider","ia_archiver","Yahoo!Slurp","YoudaoBot","YahooSlurp","MSNBot","Java(Oftenspambot)","BaiDuSpider","Voila","Yandexbot","BSpider","twiceler","SogouSpider","SpeedySpider","GoogleAdSense","Heritrix","Python-urllib","Alexa(IAArchiver)","Ask","Exabot","Custo","OutfoxBot/YodaoBot","yacy","SurveyBot","legs","lwp-trivial","Nutch","StackRambler","Thewebarchive(IAArchiver)","Perltool","MJ12bot","Netcraft","MSIECrawler","WGettools","larbin","Fishsearch","bingbot","ezooms","jikespider",);
}
/**
* 判断访问者是否为搜索引擎蜘蛛
*
* @author Eddy
* @return bool
#依赖函数 getSpiderAgent
*/
function is_crawler() {
    $flag=false;
    $agent= strtolower($_SERVER['HTTP_USER_AGENT']);
    if (!empty($agent)) {
    $spiderSite=getSpiderAgent();
    foreach($spiderSite as $val) {
        $str = strtolower($val);
        if (strpos($agent, $str) !== false) {
            $flag=true;
            break;
        }
      }
    }
    return $flag;
}
function tryCreateDir($dir) {
    if (!is_dir($dir)) {
        return mkdir($dir, '0777', true);
    }
    return true;
}
function notFound($str) {
    header('HTTP/1.1 404 NOT FOUND');
    exit('<h2>' . $str . ' not found.</h2>');
}